<template>
	<cl-dialog v-model="dialogVisible" title="客情处理" width="600px" @close="handleClose">
		<el-form
			ref="formRef"
			:model="formData"
			:rules="rules"
			label-width="120px"
			class="demo-ruleForm"
		>
			<el-form-item label="处理类型" prop="type">
				<el-radio-group v-model="formData.type">
					<el-radio :label="1">客户投诉</el-radio>
					<el-radio :label="2">质量问题</el-radio>
					<el-radio :label="3">客情下单</el-radio>
					<el-radio :label="4">其他</el-radio>
				</el-radio-group>
			</el-form-item>

			<!-- 只有客情下单类型才显示镜片数量选择 -->
      <el-form-item v-if="formData.type === 3" label="镜片数量" prop="lensType">
        <el-radio-group v-model="formData.lensType">
          <el-radio :label="1">一副镜片</el-radio>
          <el-radio :label="2">单片镜片</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 只有选择单片镜片时才显示左右眼选择 -->
      <el-form-item v-if="formData.type === 3 && formData.lensType === 2" label="镜片位置" prop="singleEyeType">
        <el-radio-group v-model="formData.singleEyeType">
          <el-radio :label="1">右眼</el-radio>
          <el-radio :label="2">左眼</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="处理内容" prop="content">
				<el-input
					v-model="formData.content"
					type="textarea"
					:rows="4"
					placeholder="请输入处理内容"
				/>
			</el-form-item>

			<el-form-item label="备注">
				<el-input
					v-model="formData.remark"
					type="textarea"
					:rows="2"
					placeholder="请输入备注信息"
				/>
			</el-form-item>
		</el-form>

		<template #footer>
			<el-button @click="handleClose">取消</el-button>
			<el-button type="primary" @click="handleSubmit">提交</el-button>
		</template>
	</cl-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue';
import { useCool } from '/@/cool';
import { ElMessage, FormInstance } from 'element-plus';

interface Props {
	modelValue: boolean;
	orderId: number;
	orderObj: any;
}

interface Emits {
	(e: 'update:modelValue', value: boolean): void;
	(e: 'closeDialog'): void;
	(e: 'success'): void;
}

const props = withDefaults(defineProps<Props>(), {
	modelValue: false,
	orderId: 0,
	orderObj: () => ({})
});

const emit = defineEmits<Emits>();

const dialogVisible = computed({
	get: () => props.modelValue,
	set: val => emit('update:modelValue', val)
});

const { service } = useCool();
const formRef = ref<FormInstance>();

const formData = reactive({
  orderId: 0,
  type: 1,
  content: '',
  lensType: 1, // 1:一副镜片, 2:单片镜片
  singleEyeType: 1, // 1:右眼, 2:左眼，仅在lensType=2时有效
  remark: ''
});

const rules = reactive({
  type: [{ required: true, message: '请选择处理类型', trigger: 'change' }],
  content: [
    { required: true, message: '请输入处理内容', trigger: 'blur' },
    { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
  ],
  lensType: [
    {
      validator: (rule, value, callback) => {
        if (formData.type === 3 && !value) {
          callback(new Error('请选择镜片数量'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ],
  singleEyeType: [
    {
      validator: (rule, value, callback) => {
        if (formData.type === 3 && formData.lensType === 2 && !value) {
          callback(new Error('请选择镜片位置（左眼/右眼）'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ]
});

// 重置表单
const resetForm = () => {
	if (formRef.value) {
		formRef.value.resetFields();
	}

	// 设置默认值
  formData.orderId = props.orderId;
  formData.type = 1;
  formData.content = '';
  formData.lensType = 1;
  formData.singleEyeType = 1;
  formData.remark = '';
};

// 监听订单ID变化
onMounted(() => {
	if (props.orderId) {
		resetForm();
	}
});

// 处理提交
const handleSubmit = async () => {
	if (!formRef.value) return;

	try {
		await formRef.value.validate();

		// 准备提交数据
		const submitData = {
			...formData,
			orderId: props.orderId,
			orderNo: props.orderObj?.orderNo || '',
			customerName: props.orderObj?.userNickName || '',
			customerPhone: props.orderObj?.userPhone || ''
		};

		// 这里应该调用实际的保存接口
		// const result = await service.order.customerRelationship.save(submitData);

		// 模拟保存成功
		console.log('保存客情处理记录:', submitData);

		ElMessage.success('提交成功');
		emit('success');
		handleClose();
	} catch (error) {
		console.error('提交失败:', error);
		ElMessage.error('提交失败，请重试');
	}
};

// 关闭弹窗
const handleClose = () => {
	dialogVisible.value = false;
	emit('closeDialog');
};

// 监听弹窗显示状态
computed(() => props.modelValue).value &&
	nextTick(() => {
		resetForm();
	});
</script>

<style scoped>
.demo-ruleForm {
	margin-top: 20px;
}
</style>
